package first.group.ssh.packet;

import first.group.ssh.SSHConsts;
import first.group.ssh.hostkey.HostKeyAlgorithm;
import first.group.ssh.hostkey.HostKeyAlgorithm.HostKey;
import first.group.ssh.hostkey.HostKeyAlgorithm.HostSignature;
import first.group.ssh.hostkey.HostKeyParser;
import first.group.ssh.hostkey.HostSignatureParser;
import first.group.ssh.packet.reader.BigIntegerReader;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.ByteBuffer;

public class DiffieHellmanGroupExchangeReplyPacket extends Packet {

    public final HostKey<? extends HostKeyAlgorithm> hostKey;
    public final BigInteger f;
    public final HostSignature<? extends HostKeyAlgorithm> hostSignature;

    public DiffieHellmanGroupExchangeReplyPacket(
            HostKey<? extends HostKeyAlgorithm> hostKey,
            BigInteger f,
            HostSignature<? extends HostKeyAlgorithm> hostSignature
    ) {
        super(SSHConsts.SSH_MSG_KEX_DH_GEX_REPLY);
        this.hostKey = hostKey;
        this.f = f;
        this.hostSignature = hostSignature;
    }

    public static PacketParser<DiffieHellmanGroupExchangeReplyPacket> PARSER = new Parser();

    private static class Parser extends PacketParser<DiffieHellmanGroupExchangeReplyPacket> {

        @Override
        public DiffieHellmanGroupExchangeReplyPacket parse(ByteBuffer buffer) throws IOException {
            var hostKey = HostKeyParser.parseHostKey(buffer);
            if (hostKey == null) {
                return null;
            }
            var f = BigIntegerReader.readBigInteger(buffer);
            if (f == null) {
                return null;
            }
            var hostSignature = HostSignatureParser.parseHostSignature(buffer);
            if (hostSignature == null) {
                return null;
            }
            if (!hostKey.getAlgorithm().equals(hostSignature.getAlgorithm())) {
                throw new IOException("Algotithms differ: key=" + hostKey.getAlgorithm().getName() + ", signature=" + hostSignature.getAlgorithm().getName());
            }
            return new DiffieHellmanGroupExchangeReplyPacket(hostKey, f, hostSignature);
        }
    }

    @Override
    public void write(ByteBuffer buffer) {
        throw new UnsupportedOperationException("Not supported yet."); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody
    }

    @Override
    public String toString() {
        return "DiffieHellmanGroupExchangeReplyPacket{" + "hostKey=" + hostKey + ", f=" + f + ", hostSignature=" + hostSignature + '}';
    }
}
